package com.bocai.kelalacar.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 作者 yuanfei on 2017/2/22.
 * 邮箱 yuanfei221@126.com
 */

public class SigUtil {

    public static String sig = "";

    public  static String setMap(Map<String,String> paramMap){
        Map<String, String> hashMap = new HashMap<>();
        hashMap.putAll(paramMap);
        hashMap.put("appid", "02544198");
        hashMap.put("nonce_str", "d1b078ed79a64f9598d6751869df2081");
//        hashMap.put("timestamp", timestamp);
        return generateSig(hashMap, "hHved2kZZ6pc1dlBYzePDc8k6wP3d7UV");
    }


    public static  String generateSig(Map<String,String> paramMap,String appKey) {
        Set<String> keySet = paramMap.keySet();
        List<String> list = new ArrayList<String>();
        for (String key : keySet) {
            if (paramMap.get(key)!=null&&!paramMap.get(key).equals("")) {
                String param = key + "=" + paramMap.get(key);
                list.add(param);
            }
        }
        Collections.sort(list,new CusttomComparator());//排序
        StringBuffer sigTempParams = new StringBuffer() ;

        for (int i = 0;i<list.size();i++) {
            sigTempParams.append(list.get(i));
            if (i!=list.size()-1){
                sigTempParams.append("&");
            }
        }
        String appKeyBefore = appKey.substring(0,16);
        String appKeyAfter = appKey.substring(16,appKey.length());

        sigTempParams.append(appKeyBefore);
        StringBuffer sig = new StringBuffer();
        sig.append(appKeyAfter).append(sigTempParams);

        return  md5(sig.toString());
    }

    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

}
